// =============================================================
// CSpaceMonitorThread
// ---------------------------------------
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr or woorung@nhncorp.com
// Date : Oct. 8, 2007
// =============================================================
#include "CSpaceMonitorThread.h"
//----------------------------------------------------------------------
CSpaceMonitorThread::CSpaceMonitorThread(char *name) 
{
	setName(name);

	space_info = NULL;
	target_space.service(CUBE_SERVICE_SPACE);
	//target_space.instance(CUBE_SERVICE_SPACE);

	data_count = 0;
}
//----------------------------------------------------------------------
CSpaceMonitorThread::~CSpaceMonitorThread() 
{
}
//----------------------------------------------------------------------
bool CSpaceMonitorThread::workspace(const char *service, const char *instance)
{
	target_space.service((char *)service);
	target_space.instance((char *)instance);
}
//----------------------------------------------------------------------
void CSpaceMonitorThread::add(CServiceInfo *space_info) 
{
	this->space_info = space_info;
}
//----------------------------------------------------------------------
void CSpaceMonitorThread::add(char *host, int port) 
{
	this->host = host;
	this->port = port;
}
//----------------------------------------------------------------------
long CSpaceMonitorThread::size()
{
	return data_count;
}
//----------------------------------------------------------------------
void CSpaceMonitorThread::monitor()
{
	CServiceProxy proxy;
	//proxy.connect(space_info->getIP(), space_info->getPort());
	proxy.connect((char *)host.c_str(), port);

	CObjectArray *pobjs = new CObjectArray(1);
	(*pobjs)[0] = new cube__CKeyValue();
	dynamic_cast<cube__CKeyValue*>((*pobjs)[0])->setKey(CUBE_SPACE_ACTION);
	dynamic_cast<cube__CKeyValue*>((*pobjs)[0])->setValue(CUBE_SPACE_SIZE);

	cube__CService space_service;
	space_service.service(target_space.service());
	space_service.instance(target_space.instance());

#ifdef DEBUG
cout << ">> monitoring service : " << space_service.service() << "(" << space_service.instance() << ")" << endl;
#endif

	struct cube__invokeResponse res;

	// invoke
	if(proxy.invoke(&space_service, pobjs, res)!=SOAP_OK) {
		soap_print_fault(proxy.soap(), stderr);

		delete (*pobjs)[0];
		delete pobjs;

		return;
	}

	CObjectArray *array = dynamic_cast<CObjectArray *>(res.out);
	if(array==NULL) {
		cout << "what the heck~~" << endl;
	}

	cube__CKeyValue *kv = dynamic_cast<cube__CKeyValue *>(array->__ptr[0]);
	if(kv!=NULL) {
		if(strcmp(kv->getKey(),CUBE_SPACE_SIZE)==0) {
			data_count = atol(kv->getValue());
		}
		else {
		}

	}

	delete (*pobjs)[0];
	delete pobjs;
}
//----------------------------------------------------------------------
void CSpaceMonitorThread::run() 
{
	monitor();
}
//----------------------------------------------------------------------
